package com.maverick.guardianangel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.ExifInterface;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

//import com.example.R;
import com.google.android.maps.GeoPoint;

public class WhereAmI extends Activity implements LocationListener{
	private static final String TAG = "CameraDemo";
	private LocationManager mlocManager;
	Bitmap bmp;
	Location imgLoc;
	Time timestamp = new Time();

	private GeoPoint currentGeoPoint;
	  Preview preview; // <1>
	  Button buttonClick; // <2>

	  /** Called when the activity is first created. */
	  @Override
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.wai);
	    
	    mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

	    //LocationListener mlocListener = new MyLocationListener();

	    mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 2.0f, this);
	    //initiateLocation();
	    preview = new Preview(this); // <3>
	    ((FrameLayout) findViewById(R.id.preview)).addView(preview); // <4>

	    buttonClick = (Button) findViewById(R.id.buttonClick);
	    buttonClick.setOnClickListener(new OnClickListener() {
	      public void onClick(View v) { // <5>
	        preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
	      }
	    });

	    Log.d(TAG, "onCreate'd");
	  }
	  

		@Override
		protected void onPause() {
			super.onDestroy();
			mlocManager.removeUpdates(this);
		}
		
		@Override
		protected void onResume() {
			super.onDestroy();
			mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 2.0f, this);
		}


	  // Called when shutter is opened
	  ShutterCallback shutterCallback = new ShutterCallback() { // <6>
	    public void onShutter() {
	      Log.d(TAG, "onShutter'd");
	      imgLoc = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
	      timestamp.setToNow();
	    }
	  };

	  // Handles data for raw picture
	  PictureCallback rawCallback = new PictureCallback() { // <7>
	    public void onPictureTaken(byte[] data, Camera camera) {
	      Log.d(TAG, "onPictureTaken - raw");
	    }
	  };

	  // Handles data for jpeg picture
	  PictureCallback jpegCallback = new PictureCallback() { // <8>
	    public void onPictureTaken(byte[] data, Camera camera) {
	      FileOutputStream outStream = null;
	      try {
	        // Write to SD Card
	    	  bmp = BitmapFactory.decodeByteArray(data, 0, data.length, null);

	    	  String filename = String.format("/sdcard/DCIM/100ANDRO/%d.jpg",
	  	            System.currentTimeMillis());
	    	  File wallpaperDirectory = new File("/sdcard/Wallpaper/");
		        wallpaperDirectory.mkdirs();
		        File outputFile = new File(wallpaperDirectory, timestamp.format2445()+".jpg");
	        outStream = new FileOutputStream(filename); // <9>
	        outStream.write(data);
	        outStream.close();
	        
	        
	        bmp.compress(CompressFormat.JPEG, 100, new FileOutputStream(outputFile));
	        
	        Image img = new Image(getApplicationContext(), outputFile.getAbsolutePath());
	        img.setLocation(imgLoc);
			img.setTimestamp(timestamp);
			img.setMake("Sony Ericsson");
			img.setModel("Xperia X10");
			
			img.setOrientation(getOrientation());
			
			img.EXIF.saveAttributes();
	      /*ExifInterface exif = new ExifInterface(filename);
            
            exif.saveAttributes();*/
	        Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
	      } catch (FileNotFoundException e) { // <10>
	        e.printStackTrace();
	      } catch (IOException e) {
	        e.printStackTrace();
	      } finally {
	      }
	      Log.d(TAG, "onPictureTaken - jpeg");
	    }
	  };
	  
	  private int getOrientation(){
			return getResources().getConfiguration().orientation;
		}

	  
	 /* public class MyLocationListener implements LocationListener 

	  {

	  @Override

	  public void onLocationChanged(Location loc)

	  {
		  loc.getLatitude();

		  loc.getLongitude();
		  String Text = "My current location is: "+

		  "Latitud = " + loc.getLatitude() +

		  "Longitud = " + loc.getLongitude() ;*/
		  //initiateLocation();
		  /*Toast.makeText( getApplicationContext(),

				  Text,

				  Toast.LENGTH_SHORT).show();
	  }
	  @Override

	  public void onProviderDisabled(String provider)

	  {

	  Toast.makeText( getApplicationContext(),

	  "Gps Disabled",

	  Toast.LENGTH_SHORT ).show();

	  }


	  @Override

	  public void onProviderEnabled(String provider)

	  {

	  Toast.makeText( getApplicationContext(),

	  "Gps Enabled",

	  Toast.LENGTH_SHORT).show();

	  }


	  @Override

	  public void onStatusChanged(String provider, int status, Bundle extras)

	  {


	  }
	  }*/
	  
	  
	  
	  /*public void initiateLocation(){
	        setCurrentGeoPoint(new GeoPoint( 
	                        (int)(mlocManager.getLastKnownLocation(
	                                        LocationManager.GPS_PROVIDER).getLatitude()*1000000.0),
	                        (int)(mlocManager.getLastKnownLocation(
	                                        LocationManager.GPS_PROVIDER).getLongitude()*1000000.0)));
	    }
	  */
	 /* @Override
      protected boolean isRouteDisplayed() {
              // TODO Auto-generated method stub
              return false;
      }*/
	  
	  /*public void setCurrentGeoPoint(GeoPoint currentGeoPoint) {
          this.currentGeoPoint = currentGeoPoint;
  }

  public GeoPoint getCurrentGeoPoint() {
          return currentGeoPoint;
  }*/
  
  public void createExifData(ExifInterface exif){
      // create a reference for Latitude and Longitude
      double lat = currentGeoPoint.getLatitudeE6()/1000000.0;
      if (lat < 0) {
          exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, "S");
          lat = -lat;
      } else {
          exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, "N");
      }
      
      exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE,
                      formatLatLongString(lat));
      
      double lon = currentGeoPoint.getLongitudeE6()/1000000.0;
      if (lon < 0) {
          exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, "W");
          lon = -lon;
      } else {
          exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, "E");
      }
      exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE,
                      formatLatLongString(lon));
      
      try {
                      exif.saveAttributes();
              } catch (IOException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
              }
              //make = android.os.Build.MANUFACTURER; // get the make of the device
              //model = android.os.Build.MODEL; // get the model of the divice
              
              /*exif.setAttribute(ExifInterface.TAG_MAKE, make);
              TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
              imei = telephonyManager.getDeviceId();
              exif.setAttribute(ExifInterface.TAG_MODEL, model+" - "+imei);*/
              
              //exif.setAttribute(ExifInterface.TAG_DATETIME, (new Date(System.currentTimeMillis())).toString()); // set the date & time

 }
  
  /*
   * formnat the Lat Long values according to standard exif format
   */
  private static String formatLatLongString(double d) {
      // format latitude and longitude according to exif format
      StringBuilder b = new StringBuilder();
      b.append((int) d);
      b.append("/1,");
      d = (d - (int) d) * 60;
      b.append((int) d);
      b.append("/1,");
      d = (d - (int) d) * 60000;
      b.append((int) d);
      b.append("/1000");
      return b.toString();
    }



@Override
public void onLocationChanged(Location location) {
	// TODO Auto-generated method stub
	location.getLatitude();

	  location.getLongitude();
	  String Text = "My current location is: "+

	  "Latitud = " + location.getLatitude() +

	  "Longitud = " + location.getLongitude() ;
	  //initiateLocation();
	  Toast.makeText( getApplicationContext(),

			  Text,

			  Toast.LENGTH_SHORT).show();
	
}

@Override
public void onProviderDisabled(String provider) {
	// TODO Auto-generated method stub
	Toast.makeText( getApplicationContext(),

			  "Gps Disabled",

			  Toast.LENGTH_SHORT ).show();
	
}

@Override
public void onProviderEnabled(String provider) {
	// TODO Auto-generated method stub
	
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
	// TODO Auto-generated method stub
	
}

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.cameramenu, menu);
    return true;
}
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) {
        case R.id.item01:    
            // Toast.makeText(this, "You pressed Gallery!", Toast.LENGTH_LONG).show();      
            startSave();             
            break;
        case R.id.item02:
        	startMap();
        case R.id.item03:     
            //Toast.makeText(this, "You pressed Exit!", Toast.LENGTH_LONG).show();          
            System.exit(0);                 
            break;
    }
    return true;
}
private void startSave(){
    Intent intent = new Intent(this,GeoGallery.class);
    //intent.setClass(GeoCamera.this, GeoGallery.class);
    startActivity(intent);
	/*TextView tv = new TextView(this);
       tv.setText("Hello, Android");
       setContentView(tv);*/
}

private void startMap(){
    Intent intent = new Intent(this,TestProviderController.class);
    //intent.setClass(WhereAmI.this, TestProviderController.class);
    startActivity(intent);
	/*TextView tv = new TextView(this);
       tv.setText("Hello, Android");
       setContentView(tv);*/
}

	}



